//
//  CurrencyOrderView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/5/2.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
let BtnTag = 1000
let TableTag = 2000
protocol CurrencyOrderDelegate:class {
    
    /// 修改筛选状态
    func changeSelectStatus(_ hiddent:Bool)
}
class CurrencyOrderView: BaseView, UITableViewDelegate, UITableViewDataSource {
    weak var delegate:CurrencyOrderDelegate?
    var btnArr:Array = [UIButton]()
    var tableArr = [UITableView]()
    var currentTableView: UITableView?
    var leverTableView: UITableView?
    var historyTableView: UITableView?
    var style:OrderType?
    var viewModel:CurrencyOrderViewModel?
    lazy var headView: UIView = {
        let view = UIView()
        view.themeBackground = ThemeManager.ThemeColorKeys.background
        return view
    }()
    
    lazy var selectLine: UIView = {
        let view = UIView()
        view.backgroundColor = kThemeColor
       return view
    }()
    
   override func setUpUI() -> Void {
    viewModel = dataSource as? CurrencyOrderViewModel
    self.style = viewModel?.type
    viewModel?.addObserver(self, forKeyPath: "refreshBool", options: [.new,.old], context: nil)
    viewModel?.addObserver(self, forKeyPath: "historyRefreshBool", options: [.new,.old], context: nil)
    viewModel?.addObserver(self, forKeyPath: "refreshPosition", options: [.new,.old], context: nil)
    
        self.addSubview(headView)
        headView.snp.makeConstraints { (make) in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(34)
        }

        let line = UIView()
        line.themeBackground = ThemeManager.ThemeColorKeys.tabLineColor
        headView.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(0.5)
        }
        var titleArr:Array = [String]()
        if style == .coinOrderType{
          titleArr = KEntrustArr
        }else {
            titleArr = KLeverEntrustArr
        }
        for i in 0..<titleArr.count {
            let btn = UIButton()
            btn.tag = BtnTag+i
            btnArr.append(btn)
            btn.themeSetTitleColor(ThemeManager.ThemeColorKeys.text2, for: UIControlState.normal)
            if i == 0 {
                btn.setTitleColor(kThemeColor , for: UIControlState.normal)
            }
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            btn.addTarget(self, action: #selector(entrustAction(sender:)), for: UIControlEvents.touchUpInside)
            btn.setTitle(titleArr[i], for: UIControlState.normal)
            headView.addSubview(btn)
            btn.snp.makeConstraints { (make) in
                make.top.bottom.equalToSuperview()
                make.left.equalToSuperview().offset(CGFloat(i)*kSCREEN_WIDTH/CGFloat(titleArr.count))
                make.width.equalTo(kSCREEN_WIDTH/CGFloat(titleArr.count))
            }
            
            let tableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.plain)
            tableView.separatorStyle = UITableViewCellSeparatorStyle.none
            tableView.tag = TableTag + i
            tableView.delegate = self
            tableView.dataSource = self
            tableView.isHidden = i == 0 ? false : true
            tableView.themeBackground = ThemeManager.ThemeColorKeys.background
            self.addSubview(tableView)
            tableView.snp.makeConstraints { (make) in
                make.top.equalToSuperview().offset(34)
                make.left.equalToSuperview()
                make.width.equalTo(kSCREEN_WIDTH)
                make.bottom.equalToSuperview()
            }
            tableArr.append(tableView)
            if i == 0 {
                currentTableView = tableView
            }else if i == 1 && self.style == .leverOrderType{
                leverTableView = tableView
            }else {
               historyTableView = tableView
                historyTableView? .mj_header = EoeRefreshHeader(refreshingTarget: self, refreshingAction: #selector(loadData(compant:)))
                historyTableView? .mj_footer = EoeRefreshFooter(refreshingTarget: self, refreshingAction: #selector(loadData(compant:)))
            }
       
        }
      headView.addSubview(selectLine)
      selectLine.snp.makeConstraints { (make) in
         make.width.equalTo(20)
         make.height.equalTo(2)
         make.bottom.equalToSuperview().offset(-2)
         make.left.equalToSuperview().offset(kSCREEN_WIDTH/CGFloat((titleArr.count*2))-10)
       }
    
    currentTableView?.creatEmptyView()
    currentTableView?.reloadData()
    historyTableView?.creatEmptyView()
    
    }
    
    /// KVO监听属性
    ///
    /// - Parameters:
    ///   - keyPath: 被监听的属性名
    ///   - object:
    ///   - change:
    ///   - context:
    @objc override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "refreshBool" {
            currentTableView?.reloadData()
        }
        if keyPath == "refreshPosition" {
            leverTableView?.reloadData()
        }
        if keyPath == "historyRefreshBool" {
            historyTableView?.reloadData()
            self.endRefresh(table: historyTableView!)
        }
        
    }
    
    //MARK: tableViewDelegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView.isEqual(currentTableView) {
            return viewModel!.currentArr.count
        }else if tableView.isEqual(leverTableView) {
            return viewModel!.positionArr.count
        }else {
            return viewModel!.historyDataArr.count
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if self.style == .leverOrderType {
            if tableView.isEqual(currentTableView) {
                let cellName = "identy"
                var cell = tableView.dequeueReusableCell(withIdentifier: cellName) as? LeverOrderCell
                if cell == nil {
                    cell = LeverOrderCell(style: .default, reuseIdentifier: cellName)
                    cell?.delegate = self
                    if self.style == .leverOrderType {
                    cell?.selectionStyle = .none
                    }
                }
                let model = (self.viewModel?.currentArr[indexPath.row])!
                cell?.exchangeOderType(model:model, type: .orderEntrust)
                return cell!
                
            }else if tableView.isEqual(leverTableView) {
                let cellName = "identy1"
                var cell = tableView.dequeueReusableCell(withIdentifier: cellName) as? LeverOrderCell
                if cell == nil {
                    cell = LeverOrderCell(style: .default, reuseIdentifier: cellName)
                    cell?.delegate = self
                }
                let model = (self.viewModel?.positionArr[indexPath.row])!
                cell?.exchangeOderType(model:model, type: .orderPosition)
                return cell!
            }else {
                let cellName = "identy2"
                var cell = tableView.dequeueReusableCell(withIdentifier: cellName) as? LeverOrderCell
                if cell == nil {
                    cell = LeverOrderCell(style: .default, reuseIdentifier: cellName)
                }
                let model = (self.viewModel?.historyDataArr[indexPath.row])!
                cell?.exchangeOderType(model:model, type: .orderHistory)
//                cell?.exchangeOderType(type: .orderHistory)
                return cell!
            }

        }
        
        let identy = "entrust"
        var cell = tableView.dequeueReusableCell(withIdentifier: identy) as? EntrustTableViewCell
        if cell == nil {
            cell = EntrustTableViewCell(style: .default, reuseIdentifier: identy)
        }
        if tableView.isEqual(currentTableView) {
        let model = viewModel?.currentArr[indexPath.row]
        cell?.isCurrent = true
        cell?.delegate = self
        cell?.stateBtn.isUserInteractionEnabled = true
        cell?.setModel(model: model!)
        }else {
            let model = viewModel?.historyDataArr[indexPath.row]
            cell?.isCurrent = false
            cell?.stateBtn.isUserInteractionEnabled = false
            cell?.setModel(model: model!)
            
        }
        return cell!
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if self.style == .leverOrderType && tableView.isEqual(historyTableView) {
            return 105
        }
        return 152
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
        //币币订单 当前有详情
        if tableView.isEqual(currentTableView) && self.style == .coinOrderType {
            let controller = CurrencyDetailsViewController()
            controller.viewModel?.type =  .orderCoinHistoryType
            if (viewModel?.currentArr[indexPath.row])!.status == 0 || (viewModel?.currentArr[indexPath.row])!.status == 1 ||
                (viewModel?.currentArr[indexPath.row])!.status == 3 || (viewModel?.currentArr[indexPath.row])!.status == 5{
                controller.viewModel?.isCurrent = true
            }
            controller.viewModel?.model = (viewModel?.currentArr[indexPath.row])!
            self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
            return
        }
        if tableView.isEqual(leverTableView) {
            let controller = CurrencyDetailsViewController()
            controller.viewModel?.type = .leverPositionType
            controller.viewModel?.model = (self.viewModel?.positionArr[indexPath.row])!
            self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
        }
        
        if tableView.isEqual(historyTableView) {
            let controller = CurrencyDetailsViewController()
            controller.viewModel?.type = self.style == .coinOrderType ? .orderCoinHistoryType : .leverHistory
            controller.viewModel?.model = (self.viewModel?.historyDataArr[indexPath.row])!
            self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
        }
    }
    
    
    @objc func entrustAction(sender:UIButton) {
        self.changeBtnStyle(sender: sender)
        selectLine.snp.remakeConstraints { (make) in
            make.width.equalTo(20)
            make.height.equalTo(2)
            make.bottom.equalToSuperview().offset(-2)
            make.centerX.equalTo(sender.centerX)
        }
        
    }
    
    func changeBtnStyle(sender:UIButton)  {
        (btnArr as NSArray).enumerateObjects { (btn, index, stop) in
            let currentBtn = btn as AnyObject as! UIButton
            let tableView = tableArr[index]
            if currentBtn .isEqual(sender) {
                viewModel?.currentSelected = index
                currentBtn.setTitleColor(kThemeColor, for: UIControlState.normal)
                if delegate != nil && delegate?.changeSelectStatus != nil {
                    self.delegate?.changeSelectStatus(tableView.isEqual(historyTableView) ? true : false)
                }
            }else {
                currentBtn.themeSetTitleColor(ThemeManager.ThemeColorKeys.text2, for: UIControlState.normal)
            }
            tableView.isHidden = tableView.tag == sender.tag + BtnTag ? false : true
        }
        
    }
    @objc func loadData(compant:UIView) {
        
        if compant.isEqual(historyTableView?.mj_header) {
            viewModel?.pageNo = 1
            viewModel?.archiveHistoryInfo()
            
        }else if compant.isEqual(historyTableView?.mj_footer){
            viewModel?.pageNo = (viewModel?.pageNo)! + 1
            viewModel?.archiveHistoryInfo()
            
        }
        
    }
    func endRefresh() {
        self.endRefresh(table: leverTableView!)
        
    }
    func endRefresh(table:UITableView) {
        table.mj_footer?.endRefreshing()
        table.mj_header?.endRefreshing()
        if table.isEqual(historyTableView) {
            if (viewModel?.historyDataArr.count)! % 10 != 0{
                table.mj_footer?.endRefreshingWithNoMoreData()
            }else {
                table.mj_footer?.endRefreshing()
            }
            table.mj_footer?.isHidden = viewModel?.historyDataArr.count != 0 ? false : true
        }
    }
    
    
    deinit {
        self.viewModel?.removeObserver(self, forKeyPath: "refreshBool", context: nil)
        self.viewModel?.removeObserver(self, forKeyPath: "historyRefreshBool", context: nil)
        self.viewModel?.removeObserver(self, forKeyPath: "refreshPosition", context: nil)
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
extension CurrencyOrderView:EntrustCellDelegate,LeverOrderCellDelegate {
    
    /// 平仓
    ///
    /// - Parameter model: model
    func changePositionState(_ model: CoinOrderModel) {
        viewModel?.selectOrderModel =  model
        viewModel?.changeLeverPosition()
    }
    
    /// 撤销订单
    ///
    /// - Parameter model: model
    func changeStates(_ model: CoinOrderModel) {
        viewModel?.selectOrderModel =  model
        if model.status == 0 || model.status == 1 || model.status == 3 || model.status == 5{
            viewModel?.cancelOrder()
        }
    }
}

